module
    .factory('BaseController', function baseController(){
        return function($scope, Modal){
            $scope.images = [];
            $scope.selected = [];
            $scope.confirmAble = false;

            $scope.confirm = function(){
                Modal.confirm(angular.copy($scope.selected));
                $scope.reset();
            }

            $scope.close = function(){
                Modal.close();
                $scope.reset();
            }

            $scope.reset = function(){
                Modal.reset();
                $scope.selected = [];
            }
        }
    })
    .factory('Modal', ['Template', 'Image', '$timeout', function(Template, Image, $timeout){

        var Modal = function(){
            if(!this.container) angular.element(document.body).append(Template);
            this.container = angular.element(document.getElementById("qiniu-container"));
            this.gallery = angular.element(document.getElementsByClassName('wx-gallery'));
            this.uploader = angular.element(document.getElementsByClassName('wx-uploader'));
        };

        Modal.prototype.open = function(scope){
            this.scope = scope;
            if(!this.scope.quantity) this.scope.quantity = 1;
            this.container.removeClass('wx-hide');
            this.gallery.removeClass('wx-hide');
        };

        Modal.prototype.close = function(){
            this.reset();
        }

        Modal.prototype.reset = function(){
            this.container.addClass('wx-hide');
            this.gallery.addClass('wx-hide');
            this.uploader.addClass('wx-hide');
            angular.element(document.getElementsByClassName('wx-list')).removeClass('selected');
        }

        Modal.prototype.switch = function(type){
            this.gallery.addClass('wx-hide');
            this.uploader.addClass('wx-hide');
            this[type].removeClass('wx-hide');
        }

        Modal.prototype.confirm = function(data){
            if(this.scope.callback){
                this.scope.callback(data);
            }else{
                if(this.scope.quantity > 1){
                    this.scope.ngModel = data;
                }else{
                    this.scope.ngModel = data[0];
                }
            }

            this.close();
        }

        return new Modal();
    }])
    .controller('qiniuGalleryCtrl', ['$scope', 'Modal', 'BaseController', '$rootScope', 'Image', function($scope, Modal, BaseController, $rootScope, Image){

        angular.extend(this, new BaseController($scope, Modal));

        $scope.sync = function(){
            Image.all().success(function(callback){
                $scope.images = callback.data;
                console.log($scope.images)
            });
        }

        $scope.sync();

        $scope.$on('sync', function(){
            $scope.sync();
        });

        $scope.goToUpload = function(){
            Modal.switch('uploader');
            $rootScope.$broadcast('uploaderInit');
        }

        $scope.select = function(index, event){
            var li = angular.element(event.target.offsetParent);
            var lis = angular.element(document.getElementsByClassName('wx-list'));

            var image = $scope.images[index];

            if(li.hasClass('selected')){
                var image = $scope.images[index];
                var cindex = $scope.selected.indexOf(image);
                angular.forEach($scope.selected, function(val, key){
                    if(val.media_id == image.media_id);
                    $scope.selected.splice(key, 1);
                    li.removeClass('selected');
                });
            }else{
                if(Modal.scope.quantity == $scope.selected.length) {
                    if(Modal.scope.quantity == 1){
                        $scope.selected = [angular.copy($scope.images[index])];
                        lis.removeClass('selected');
                        li.addClass('selected');
                    }else{
                        return false;
                    }
                }else{
                    $scope.selected.push(angular.copy(image));
                    li.addClass('selected');
                }
            }

            $scope.confirmAble = (Modal.scope.quantity >= $scope.selected.length && $scope.selected.length > 0)
        }

    }])
    .controller('qiniuUploaderCtrl', ['$scope', 'Modal', 'BaseController', 'Config', '$rootScope', function($scope, Modal, BaseController, Config, $rootScope){
        angular.extend(this, new BaseController($scope, Modal));

        $scope.files = [];
        $scope.selected = [];
        $scope.status = 'queue';
        var uploader,
            progressBar = document.getElementsByClassName('wx-progress');

        $scope.init = function(){
            // 初始化Web Uploader
            uploader = WebUploader.create({
                dnd: ".wx-uploader .wx-dnd",
                // 选完文件后，是否自动上传。
                auto: false,

                formData: {
                    token: Config.token
                },

                // swf文件路径
                //swf: 'http://localhost/weazm/project/angular-qiniu-uploader/dist/js/Uploader.swf',

                // 文件接收服务端。
                server: 'http://upload.qiniu.com/',

                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#wx-picker',

                // 只允许选择图片文件。
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/*'
                }
            });

            uploader.on('fileQueued', function( file ) {
                uploader.makeThumb( file, function( error, src ) {
                    $scope.files.push({
                        file: file,
                        src: src,
                        percentage: 0
                    });
                    $scope.images.push(src);
                    $scope.$apply();
                }, 100, 100 );
            });

            uploader.on( 'uploadProgress', function( file, percentage ) {
                angular.forEach($scope.files, function(val, key){
                    if(val.file.id == file.id){
                        $scope.files[key]['percentage'] = (percentage * 100).toFixed(0);
                        $scope.$apply();
                    }
                });
            });

            uploader.on( 'uploadError', function( file ) {

            });

            uploader.on( 'uploadSuccess', function( file, res) {
                console.log(res)
                angular.forEach($scope.files, function(val, key){
                    if(val.file.id == file.id){
                        angular.element(document.getElementsByClassName('upload-item')[key]).addClass('uploaded');
                    }
                })
                $scope.selected.push(res.data);
                if($scope.selected.length == $scope.images.length){
                    $scope.status = 'success';
                    $rootScope.$broadcast('sync');
                    $scope.$apply();
                    alert('上传完成!');
                }
            });
        }

        $scope.$on('uploaderInit', function(){

            $scope.init();

        });

        $scope.remove = function(index){
            uploader.removeFile($scope.files[index]['file']);
            $scope.images.splice(index, 1);
            $scope.files.splice(index, 1);
        }

        $scope.startUpload = function(){
            uploader.upload();
            $scope.status = 'uploading';
        }

        $scope.cancelUpload = function(){
            uploader.stop();
            $scope.reset();
        }

        $scope.reset = function(){
            $scope.files = [];
            $scope.images = [];
            $scope.selected = [];
            $scope.status = 'queue';
            uploader.reset();
            $scope.init();
        }


        $scope.goToGallery = function(){
            Modal.switch('gallery');
            $scope.reset();
        }

    }]);
